import { getCalendar } from '../../utils/request';
import { patchUserCollection } from '../../utils/request';
Page({
  data: {
    weekDates: [],
    timetable: {},
    todayIndex: -1,
    showCollectionPopup: false,
    showPopup: false,
    selectedItem: null
  },

  async onLoad() {
    const res = await getCalendar();
    const today = new Date();
    const todayIndex = today.getDay(); // 0: 周日, ..., 6: 周六
  
    // 生成从今天起连续 7 天的 weekDates（带滚动）
    const weekDates = Array.from({ length: 7 }, (_, i) => {
      const date = new Date();
      date.setDate(today.getDate() + i);
      return {
        id: date.getDay(), // 用于匹配 weekday.id
        label: '周' + '日一二三四五六'.charAt(date.getDay())
      };
    });
  
    // 获取从今天起 7 天内的 weekday.id（顺序为今天 → 后 6 天）
    const next7DayIds = weekDates.map(day => day.id);
  
    // 构造 timetable，仅包含未来 7 天的内容
    const timetable = {};
    res.forEach(day => {
      const dayId = day.weekday.id;
      if (!next7DayIds.includes(dayId)) return; // 过滤掉不在未来7天内的
  
      if (!timetable[dayId]) timetable[dayId] = [];
  
      day.items.forEach((anime, index) => {
        timetable[dayId].push({
          id: anime.id,
          imageUrl: anime.images?.large.replace('http://', 'https://') || '',
          nameCn: anime.name_cn || '',
          name: anime.name || '',
          //infoItems: [anime.air_date || '未知播出时间'],
          rank: anime.rank || '',
          ratingScore: anime.rating?.score?.toString() || '',
          ratingTotal: anime.rating?.total?.toString() || '',
          collection: 'doing',
          weekDayText: '周' + '日一二三四五六'.charAt(dayId),
          airTime: anime.airtime || '00:00',
          isFirstOfDay: index === 0,
          roast: anime.comment || ''
        });
      });
    });
  
    // 更新页面数据
    this.setData({
      weekDates,
      timetable,
      todayIndex
    }, () => {
      setTimeout(() => {
        this.setData({ todayIndex });
      }, 300);
    });
  },
  
  // 点击卡片跳转详情页
  onCardClick(e) {
    const cardId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/item-detail/item-detail?id=${cardId}`,
    });
  },

  // 点击收藏按钮处理收藏逻辑
  onCardCollect(e) {
    const { itemData } = e.detail;
    if (!itemData) {
      console.warn('没有传入 itemData');
      return;
    }
    this.setData({
      showCollectionPopup: true,
      selectedItem: itemData,
    });
  },
  onCloseCollectionPopup() {
    this.setData({ showCollectionPopup: false });
  },

  async onCollectionSubmit(e) {
    const { formData } = e.detail;
    if (!formData) return;

    const id = this.data.selectedItem?.id;
    if (!id) {
      console.error('未找到选中项id，无法更新');
      return;
    }

    const timetable = { ...this.data.timetable };
    for (const dayId in timetable) {
      timetable[dayId] = timetable[dayId].map(item => {
        if (item.id === id) {
          return {
            ...item,
            ...formData,
            ratingScore: Number(formData.ratingScore)
          };
        }
        return item;
      });
    }

    try {
      const payload = {
        type: this.reverseMapCollectionType(formData.collection),
        rate: formData.ratingScore,
        comment: formData.roast,
        private: formData.isPrivate
      };
      await patchUserCollection(id, payload);

      wx.showToast({
        title: '收藏状态已更新',
        icon: 'success'
      });
    } catch (error) {
      console.error('上传收藏状态失败:', error);
      wx.showToast({
        title: '收藏状态上传失败',
        icon: 'none'
      });
    }

    this.setData({
      timetable,
      showCollectionPopup: false,
      selectedItem: null
    });
  },

  // 和收藏页一样，添加状态映射函数
  reverseMapCollectionType(type) {
    const map = {
      'wish': 1,
      'collect': 2,
      'doing': 3,
      'on_hold': 4,
      'dropped': 5
    };
    return map[type] || 0;
  }
});